【问题标题】:Can someone explain the following code for me?有人可以为我解释以下代码吗?
【发布时间】:2023-04-02 08:27:01
【问题描述】:

我正在尝试理解 Promise。但在这里我很困惑。 我想创建一个测试函数,它将在 3 秒后打印 3000,然后在 2 秒后打印 2000,然后在 1 秒后打印 1000。这是我的代码:

'use strict';
var Q = require('q');

function delayConsole(timeOut) {
    var defer = Q.defer();
    setTimeout(function(){
        console.log(timeOut);
        defer.resolve(2000);
    },timeOut);
    return defer.promise;
}

// This works
delayConsole(3000).then(function(){
    return delayConsole(2000);
}).then(function(){
    return delayConsole(1000);
    });

// This doesn't work. Why?
delayConsole(3000).then(delayConsole(2000)).then(delayConsole(1000));

【问题讨论】:

    标签: javascript node.js promise q


    【解决方案1】:

    在那里,您立即调用函数delayConsole

    .then(delayConsole(2000))
    

    也就是说:你不传递函数,而是函数调用的结果,你不等待承诺被链接。

    当你这样做时

    then(function(){
        return delayConsole(2000);
    })
    

    然后您传递一个函数,而不是该函数调用的结果。当 Promise 链中的前一个元素被解决时,可以调用该函数。

    【讨论】:

    • 值得一提的是,Q 附带了 .delay 函数。
    • 这解释了很多。谢谢
    【解决方案2】:

    我只是想和大家分享一下,你可以让这个有时更容易使用的建筑工作:

    promise.then(delayConsole(3000)).then(delayConsole(2000)).then(delayConsole(1000));
    

    通过将delayConsole() 更改为:

    function delayConsole(timeOut) {
        return function() {
            var defer = Q.defer();
            setTimeout(function(){
                console.log(timeOut);
                defer.resolve(2000);
            },timeOut);
            return defer.promise;
        }
    }
    

    这样,调用delayConsole() 只会捕获超时参数并返回一个函数,该函数稍后可以由promise .then 处理程序调用。因此,您仍然将函数引用传递给 .then() 处理程序,它允许承诺引擎稍后调用内部函数,而不是现在执行它。

    【讨论】:

    • 感谢 jfriend00。你们太棒了!
    猜你喜欢
    • 1970-01-01
    • 2012-04-09
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多