【发布时间】:2018-05-18 22:46:15
【问题描述】:
我正在寻找一种方法来无限调用带有承诺的函数。 我尝试了两种情况,一种有效,另一种无效。 不起作用的代码的目的是:从 API 获取数据,然后将其存储到数据库中。
我正在学习承诺,有人可以解释一下为什么一个有效而另一个无效吗? 在我的代码下方
工作代码 该函数只被调用一次,我希望它被无限调用
const request = require('request') //node to facilitate http request
var nano = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
var db_name = nano.db.use('bitfinex'); //couchdb database name
var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
var nonce = new Date().toISOString() //gives a unique id
.replace(/T/, ' ') // replace T with a space
.replace(/\..+/, '') // delete the dot and everything after
let cleanTheRoom = function() {
return new Promise(function(resolve, reject) {
resolve('Cleaned the Room, ');
});
};
let removedTheGarbage = function(msg) {
return new Promise(function(resolve, reject) {
resolve(msg + 'removed the garbage, ');
});
};
let getIcecream = function(msg) {
return new Promise(function(resolve, reject) {
resolve(msg +'got icecream.');
});
};
setInterval(function(){
cleanTheRoom()
.then(removedTheGarbage)
.then(getIcecream)
.then(function(msg) {
console.log(msg );
});
}, 2000);
失败代码
const request = require('request') //node to facilitate http request
var nano = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
var db_name = nano.db.use('bitfinex'); //couchdb database name
var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
var nonce = new Date().toISOString() //gives a unique id
.replace(/T/, ' ') // replace T with a space
.replace(/\..+/, '') // delete the dot and everything after
// get current litecoin price from Bitfinex
function getLtcPrice(){
return new Promise(function(resolve, reject){
request.get(ltc_url,
function (error, response, body) {
var rep = JSON.parse(body);
var ltc_price = rep.ask;
resolve (ltc_price)
if (error){
reject(ltc_price)
}
});
})
}
//save current litecoin price to the database
function saveLtcPrice (ltc_price){
return new Promise(function(resolve, reject){
resolve(
db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
function(err, body) {
if (!err)
console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
})
)
});
}
setInterval(function(){
getLtcPrice()
.then(function(ltcPrice){
saveLtcPrice(ltcPrice);
});
}, 2000);
【问题讨论】:
-
您收到了哪些错误消息。你能提供更多信息吗?
-
如果再次触发 setInterval 的处理程序时之前的调用尚未完成怎么办?它应该等待之前的请求完成吗?
-
@ZombieChowder :我实际上没有收到任何错误消息,只是它只运行一次
标签: javascript node.js api promise setinterval