承诺不能在nodejs的cronjob中工作。
让我用这段代码来解释我的问题。
我有一个cron每五秒钟运行一次。
现在在cron中我有一个函数client.statistics我想这需要一些时间。所以我需要等待,然后在下面的代码运行。
问题:问题是我使用的代码没有承诺,所以我知道没有承诺它不工作。现在我使用promise来等待该函数时间,但目前不工作。
我用诺言,现在却像这样离开。
:——cron start——DATE-TIME 20121-10-22 11:41:10
不执行下面的代码,不知道这里发生了什么
我需要什么:我需要First ExecuteTop Codethen承诺代码然后最后代码
谢谢先进。:)
const twelvedata = require("twelvedata");
cron.schedule('*/5 * * * * *', () => {
var today = new Date();
var datetime = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('--- CRON START ---');
console.log('DATE-TIME', datetime);
let symbol = "5PAISA";
let params = {
symbol:symbol,
exchange: "NSE",
country: "India",
};
let mypromise = function functionOne(){
const client = twelvedata(config);
return new Promise((resolve ,reject)=>{
client.statistics(params).then((data) => {
console.log("All Worked",data);
resolve("Resolved");
}).catch((error) => {
console.log('Error', error);
reject("Rejected")
});
});
};
mypromise().then((res)=>{
console.log(`The function recieved with value ${res}`)
console.log('--- CRON END ---');
return datetime;
}).catch((error)=>{
console.log(`Handling error as we received ${error}`);
console.log('ERROR');
return false;
});
console.log('--- CRON FINISHED ---');
});
首先你的new Promise((resolve ,reject)=>{ … })
是一个反模式,因为你在里面创建了一个承诺链。
另外,reject("Rejected")
通常被认为是一个反模式,因为reject("Rejected")
被认为等同于throw "Rejected"
的含义,你应该只抛出实际的错误。
console.log('--- CRON FINISHED ---');
不等待承诺链完成,而是立即被调用。
这是你的代码的清理版本。
const twelvedata = require("twelvedata");
cron.schedule('*/5 * * * * *', () => {
var today = new Date();
var datetime = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('--- CRON START ---');
console.log('DATE-TIME', datetime);
let symbol = "5PAISA";
let params = {
symbol: symbol,
exchange: "NSE",
country: "India",
};
twelvedata(config)
.statistics(params)
.then((data) => {
console.log("All Worked", data);
return "Resolved"
}).catch((error) => {
console.log('Error', error);
return "Rejected"
}).then((res) => {
console.log(`The function recieved with value ${res}`)
console.log('--- CRON END ---');
// you don't make use of this returned value in your code ?
// return datetime;
}).catch((error) => {
console.log(`Handling error as we received ${error}`);
console.log('ERROR');
// you don't make use of this returned value in your code ?
// return false;
})
.finally(() => {
console.log('--- CRON FINISHED ---');
});
});
正如我所说的reject("Rejected")
是一个反模式,在你的情况下,它不清楚为什么你甚至把实际的错误翻译成Rejected
,你可以让错误传递到你的console.log(`Handling error as we received ${error}`);
。
const twelvedata = require("twelvedata");
cron.schedule('*/5 * * * * *', () => {
var today = new Date();
var datetime = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('--- CRON START ---');
console.log('DATE-TIME', datetime);
let symbol = "5PAISA";
let params = {
symbol: symbol,
exchange: "NSE",
country: "India",
};
twelvedata(config)
.statistics(params)
.then((data) => {
console.log("All Worked", data);
return "Resolved"
})
.then((res) => {
console.log(`The function recieved with value ${res}`)
console.log('--- CRON END ---');
return datetime;
})
.catch((error) => {
console.log(`Handling error as we received ${error}`);
console.log('ERROR');
return false;
})
.finally(() => {
console.log('--- CRON FINISHED ---');
});
});
使用async
和await
可以使整个事情更加清晰。
const twelvedata = require("twelvedata");
cron.schedule('*/5 * * * * *', async() => {
var today = new Date();
var datetime = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('--- CRON START ---');
console.log('DATE-TIME', datetime);
let symbol = "5PAISA";
let params = {
symbol: symbol,
exchange: "NSE",
country: "India",
};
// I commented that out because you acutall don't use that in your code, but is would it shows how to match your `return` statements in the promise chain.
// let result;
try {
const data = await twelvedata(config).statistics(params)
console.log("All Worked", data);
const res = "Resolved"
// result = datetime;
console.log(`The function recieved with value ${res}`);
console.log('--- CRON END ---');
} catch (error) {
// result = false;
console.log(`Handling error as we received ${error}`);
console.log('ERROR');
}
// console.log(result)
console.log('--- CRON FINISHED ---');
});
并删除所有似乎不使用的内容:
const twelvedata = require("twelvedata");
cron.schedule('*/5 * * * * *', async() => {
var today = new Date();
var datetime = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('--- CRON START ---');
console.log('DATE-TIME', datetime);
let symbol = "5PAISA";
let params = {
symbol: symbol,
exchange: "NSE",
country: "India",
};
try {
const data = await twelvedata(config).statistics(params)
console.log("All Worked", data);
console.log('--- CRON END ---');
} catch (error) {
console.log(`Handling error as we received ${error}`);
console.log('ERROR');
}
console.log('--- CRON FINISHED ---');
});
与其在functionOne
中返回一个新的承诺,不如尝试将一个承诺赋值给mypromise
变量。
let mypromise = new Promise((resolve ,reject) => {
const client = twelvedata(config);
client.statistics(params).then((data) => {
console.log("All Worked",data);
resolve("Resolved");
}).catch((error) => {
console.log('Error', error);
reject("Rejected")
});
});
现在不用调用:
mypromise.then((res)=>{
console.log(`The function recieved with value ${res}`)
console.log('--- CRON END ---');
return datetime;
}).catch((error)=>{
console.log(`Handling error as we received ${error}`);
console.log('ERROR');
return false;
}).finally(() => {
console.log('--- CRON FINISHED ---')
})
你不需要你自己的基于承诺的包装API,因为你正在使用的API已经返回承诺
考虑重写代码,这样你就不用使用那么多的承诺和嵌套的回调了。
这个(未经测试的)版本的代码只有2级缩进,没有回调(忽略它都在对cron.schedule的调用中),并且缩短了6行。
const twelvedata = require("twelvedata");
cron.schedule('*/5 * * * * *', async () => {
try
{
var today = new Date();
var datetime = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
console.log('--- CRON START ---');
console.log('DATE-TIME', datetime);
let symbol = "5PAISA";
let params = {
symbol:symbol,
exchange: "NSE",
country: "India",
};
const client = twelvedata(config);
const data = await client.statistics(params);
console.log(`The function recieved with value ${data}`)
console.log('--- CRON END ---');
return datetime;
}
catch (error)
{
console.log(`Handling error as we received ${error}`);
console.log('ERROR');
return false;
}
finally
{
console.log('--- CRON FINISHED ---');
}
});