2017-11-10 46 views
-2

我有2個回調其中一個。javascript node.js從回調分配變量到外部變量

service.call(data).then(result=>{ 

var err=''; 
service2.call(result.data, (result2,error)=>{ 
    //I want to assign error to err 
}) 
}) 

如何將內部變量賦值給外部變量?

+1

當函數做什麼它應該@ibrahimmahrir回調被調用,那麼我不認爲這些回調的異步調用,因爲它們是嵌套在回調中,鏈接有不同的故事 – wrangler

+0

@avalon如果你這樣做'err = error'在第二次回調中會按照它的設想工作,但如果在回調返回值之前使用err的其他地方,它將會是未定義的。因此,它取決於'err = error'後面的目的是什麼? – wrangler

+0

@wrangler根據nodejs哲學,它最可能是一個異步函數。 OP可能已經嘗試自己分配值。 –

回答

-1

您可以簡單地在service2回調中使用err = error賦值。 另一個問題是,err變量只存在於第一個服務的回調中,所以目前還不清楚你將如何使用它。 無論如何,我已經草擬了幾個模擬服務來表明這個任務是有效的。

// this is mock 'service' 
const service = { 
    call: (data) => { 
     console.log('service is called with "' + data + '"'); 
     // returning Promise because 'then' is used in consuming code 
     return new Promise((resolve, reject) => { 
      setTimeout(() => resolve({ data: '"This is result of call to service"' }), 1000); 
     }) 
    } 
} 

// this is mock 'service2' 
const service2 = { 
    // no Promise here because there is no 'then' in consuming code 
    call: (data, callback) => { 
     console.log('service2 is called with ' + data); 
     //setTimeout(() => callback('"This is result of call to service2 with ' + data + '"'), 1000); // this would be success scenario 
     setTimeout(() => callback(null, "service 2 failed"), 2000);  // this is a failure scenario 
    } 
} 

// now call the services 
service.call('data').then(result => { 
    console.log("service completed with " + JSON.stringify(result)); 
    var err = ''; 
    service2.call(result.data, (result2, error) => { 
     if (error) { 
      console.log('service2 failed with message "' + error + '"'); 
      err = error; 
     } 
    }) 

    // we're setting timeout big enough for service2 to complete to give it a chance to chang err variable before it's written to console 
    setTimeout(() => { 
      console.log('ultimate value of "err" variable is "' + err + '"'); 
     }, 
     5000  // you may try it with 1000 delay to see unchanged value 
    ) 
})