亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的變量在函數內部修改后沒有變化? - 異步代碼引用

為什么我的變量在函數內部修改后沒有變化? - 異步代碼引用

鑒于以下示例,為什么outerScopeVar在所有情況下都未定義?var outerScopeVar;var img = document.createElement('img');img.onload = function() {     outerScopeVar = this.width;};img.src = 'lolcat.png';alert(outerScopeVar);var outerScopeVar;setTimeout(function() {     outerScopeVar = 'Hello Asynchronous World!';}, 0);alert(outerScopeVar);// Example using some jQueryvar outerScopeVar;$.post('loldog', function(response) {     outerScopeVar = response;});alert(outerScopeVar);// Node.js examplevar outerScopeVar;fs.readFile('./catdog.html', function(err, data) {     outerScopeVar = data;});console.log(outerScopeVar);// with promisesvar outerScopeVar;myPromise.then(function (response) {     outerScopeVar = response;});console.log(outerScopeVar);// geolocation APIvar outerScopeVar;navigator.geolocation.getCurrentPosition(function (pos) {     outerScopeVar = pos;});console.log(outerScopeVar);為什么undefined在所有這些例子中輸出?我不想要解決方法,我想知道為什么會這樣。
查看完整描述

3 回答

?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

對于正在尋找快速參考的人以及使用promises和async / await的一些示例,這里有一個更簡潔的答案。

對于調用異步方法(在本例中setTimeout)并返回消息的函數,從樸素方法(不起作用)開始:

function getMessage() {
  var outerScopeVar;
  setTimeout(function() {
    outerScopeVar = 'Hello asynchronous world!';
  }, 0);
  return outerScopeVar;}console.log(getMessage());

undefined在這種情況下記錄,因為getMessagesetTimeout調用回調之前返回并更新outerScopeVar。

解決它的兩種主要方法是使用回調承諾

回調

這里的更改是getMessage接受一個callback參數,該參數將被調用以在可用時將結果傳遞回調用代碼。

function getMessage(callback) {
  setTimeout(function() {
    callback('Hello asynchronous world!');
  }, 0);}getMessage(function(message) {
  console.log(message);});

承諾

Promise提供了一種比回調更靈活的替代方案,因為它們可以自然地組合起來協調多個異步操作。甲承諾/ A +標準實現天然地在node.js中(0.12+)和許多當前瀏覽器提供的,而是在像庫還實現藍鳥Q。

function getMessage() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Hello asynchronous world!');
    }, 0);
  });}getMessage().then(function(message) {
  console.log(message);  });

jQuery Deferreds

jQuery提供的功能類似于Deferreds的promises。

function getMessage() {
  var deferred = $.Deferred();
  setTimeout(function() {
    deferred.resolve('Hello asynchronous world!');
  }, 0);
  return deferred.promise();}getMessage().done(function(message) {
  console.log(message);  });

異步/ AWAIT

如果您的JavaScript環境包括支持asyncawait(如Node.js的7.6+),那么你就可以在同步使用承諾async的功能:

function getMessage () {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve('Hello asynchronous world!');
        }, 0);
    });}async function main() {
    let message = await getMessage();
    console.log(message);}main();


查看完整回答
反對 回復 2019-05-20
  • 3 回答
  • 0 關注
  • 1303 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號