簡體   English   中英

從promise中無法訪問的變量

[英]variable not accessible from promise's then

我有一個奇怪的情況,我不是什么原因造成的。 我有一個函數,它返回一個promise並將其鏈接到一個'then'方法。 在then方法內部,我可以訪問一個外部變量,但另一個未定義。

我以為我可能在'then'函數中使用了該名稱,並且由於提升,該值是不確定的,但是沒有。

這是我的案例的簡化版本,想知道是什么導致這種情況:

class MessageSender {
    constructor(){
    }

    sendMessage(message, options) {
        return somethingThatReturnPromise()
            .then(function (response) {
                // parameter 'message' is object as it should be,
                // but'options' is undefined.
                return response;
            })
        return promise;
    }
}

謝謝

它似乎工作正常。

function sendMessage(message, options) {
    return somethingThatReturnPromise()
    .then(function (response) {
        console.log('message: ' + message);
        console.log('options: ' + options);
        return response;
    });
}

function somethingThatReturnPromise(){
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve();
        }, 100);
    });
}

console.log('Starting...');
sendMessage('THE MESSAGE', 'THE OPTIONS').then(function(){
    console.log('All done.');
});

退貨

me@pc:~/dev/test$ node asdf.js 
Starting...
message: THE MESSAGE
options: THE OPTIONS
All done.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM