简体   繁体   English

有人可以为我解释以下代码吗?

[英]Can someone explain the following code for me?

I'm trying to understand Promise. 我试图了解Promise。 But here I'm confused. 但是在这里我很困惑。 I want to create a test function that will print 3000 after 3 second, then print 2000 after 2 second, then print 1000 after 1 second. 我想创建一个测试功能,将在3秒后打印3000,然后在2秒后打印2000,然后在1秒后打印1000。 Here is my code: 这是我的代码:

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

There, you call the function delayConsole immediately : 在那里,您立即调用函数delayConsole

.then(delayConsole(2000))

That is : you don't pass the function but the result of the function call, you don't wait for the promises to be chained. 那就是:您不传递函数,而是函数调用的结果,您不必等待promise被链接。

When you do 当你做

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

then you pass a function, not the result of that function call. 那么您传递一个函数,而不是该函数调用的结果。 The function can be called when the previous element in the promise chain is solved. 当解决了promise链中的前一个元素时,可以调用该函数。

I just thought I'd share that you can make this construction work which is sometimes easier to use: 我只是想与您分享,您可以使此构造工作有时更易于使用:

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

by changing delayConsole() to this: 通过将delayConsole()更改为此:

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

This way, calling delayConsole() just captures the timeout argument and returns a function that can be called later by the promise .then handler. 这样,调用delayConsole()只是捕获超时参数并返回一个函数,以后可以由promise .then处理程序调用。 So, you are still passing a function reference to the .then() handler which lets the promise engine call the internal function sometime later rather than execute it now. 因此,您仍将函数引用传递给.then()处理函数,该处理函数允许promise引擎稍后再调用内部函数,而不是立即执行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM