Nodejs承诺不能正常工作?

时间:2015-12-03 06:45:51

标签: javascript node.js asynchronous promise

我正在使用nodejs和图书馆Promises / A +(选择这个,因为它似乎是最受欢迎的)https://www.npmjs.com/package/promise。我面临的问题是即使async函数正在完成它,它也会在失败语句之后完成。所以sv + ' No it failed'始终在console.log消息(表明它成功)之前打印。我在异步方法中。这个console.log消息应该在async方法之前打印。我被困了为什么会发生这种情况?承诺总是在失败的情况下运行,即使异步方法返回成功了吗?

我的代码:

 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');
    });

2 个答案:

答案 0 :(得分:4)

你的async方法存在问题,它应该是异步函数

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
}

注意:顾名思义,这个答案认为asyncmethod是异步

答案 1 :(得分:0)

你做错了,你读过有关承诺的任何文件吗? 首先,您不需要额外的包,nodejs已经包含Promise。

如果private static float baseLength() { float baseLength = 0; Scanner user_input = new Scanner(System.in); while (baseLength <= 0) { try { System.out.print("Enter the base length of the triangle: "); baseLength = user_input.nextFloat(); if (baseLength <= 0) { System.out.println("Error. Plase enter a number higher than 0."); } } catch (InputMismatchException badChar) { System.err.println("You have entered a bad value. Please try again"); } } return baseLength; } 是承诺,您可以直接执行此操作:

asyncMethod