JavaScript Promise - 如何做出多重承诺?

JavaScript Promise - how to make multiple promise?

如何链接多重承诺?例如:

var promise = new Promise(function(resolve, reject) {

    // Compose the pull url.
    var pullUrl = 'xxx';

    // Use request library.
    request(pullUrl, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // Resolve the result.
            resolve(true);
        } else {
            reject(Error(false));
        }
    });

});

promise.then(function(result) {

    // Stop here if it is false.
    if (result !== false) {
        // Compose the pull url.
        var pullUrl = 'xxx';

        // Use request library.
        request(pullUrl, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body); // <-- I want to pass the result to the next promise.
            } else {
                reject(Error(false));
            }
        });
    }

}, function(err) {
    // handle error
});

promise.then(function(result) {

    // Stop here if it is false.
    if (result !== false) {
        // handle success.
        console.log(result);
    }
}, function(err) {
    // handle error.
});

错误:

resolve(body); ReferenceError: resolve is not defined

有什么想法吗?

当链接 Promise 时,return 给定函数的值 then 应该是一个 Promise,或者是要传递的值。

在您的情况下,由于您正在进行异步调用,因此您只需 return 另一个承诺并在其中调用 rejectresolve。如果它不是异步的,你可以只 return 这个值,或者抛出一个错误,它也会被传递给下一个 then 或错误 handler/catch 视情况而定。

此外,您需要将它们链接在一起,因为每个 then() return 是一个不同的 Promise。

所以,像这样:

var promise = new Promise(function(resolve, reject) {

    // Compose the pull url.
    var pullUrl = 'xxx';

    // Use request library.
    request(pullUrl, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // Resolve the result.
            resolve(true);
        } else {
            reject(Error(false));
        }
    });

});

promise.then(function(result) {

    // Stop here if it is false.
    if (result !== false) {
        var airportCode = result;

        // Compose the pull url.
        var pullUrl = 'xxx';

        // Use request library.
        return new Promise(function (resolve, reject) {
            request(pullUrl, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    resolve(body);
                } else {
                    reject(Error(false));
                }
            });
        });
    }

}).then(function(result) {
    // Stop here if it is false.
    if (result !== false) {
        // handle success.
        console.log(result);
    }
}).catch(function (err) {
  // handle error
});

这是一个具有工作版本的 JSFiddle:JSFiddle