use*_*127 3 javascript asynchronous node.js promise
我正在使用nodejs和库Promises / A +(选择它似乎是最受欢迎的库)https://www.npmjs.com/package/promise。我面临的问题是,即使异步功能已按预期完成,但在失败声明后仍已完成。因此sv + ' No it failed'
,总是在async方法中的console.log消息(表明成功)之前打印此消息。此console.log消息应该先打印出来,因为它在async方法内部。我被困住为什么会这样?即使异步方法成功返回后,promise也总是在失败时运行?
我的代码:
var promise = new Promise(function (resolve, reject) {
var u = asyncmethod(some_var);
if (u){
resolve(some_var)
}
else{
reject(some_var);
}
});
promise.then(function(sv) {
console.log(sv + ' Yes it worked');
}, function(em) {
console.log(sv + ' No it failed');
});
Run Code Online (Sandbox Code Playgroud)
您的异步方法有问题,应该是异步功能
var promise = new Promise(function (resolve, reject) {
//var u = asyncmethod(some_var); // <-- u is not defined, even if you return result stright, as it's the nature of async
asyncmethod(some_var, function(err, result){ //pass callback to your fn
if(err){
reject(err);
} else {
resolve(result);
}
});
});
promise.then(function(successResponse) { //better name variables
console.log(successResponse + ' Yes it worked');
}, function(errorResponse) {
console.log(errorResponse + ' No it failed');
});
//and simple implementation of async `asyncmethod`
var asyncmethod = function(input, callback){
setTimeout(function(){
callback(null, {new_object: true, value: input});
}, 2000); //delay for 2seconds
}
Run Code Online (Sandbox Code Playgroud)
注意:顾名思义,此答案认为asyncmethod
是异步的