2017-07-30 39 views
2

JavaScript有點新鮮。 一直在處理承諾,但遇到了一個問題,我不知道如何處理。將一個承諾的值傳遞給下一個

我該如何將價值傳遞給下一個承諾的決心?

這裏是我的代碼

bot.on('ask.add_account_password', (msg) => { 
    let username = users[msg.from.id].username; 
    let password = msg.text; 
    var accounts = require('./inc/account.js'); 
    accounts.login_account(username,password).then(function(data){ 
     var account = data.params; 
     console.log(account); 
     return accounts.store(msg.from.id,username,password,account.followerCount); 
    }).then(function(data){ 
     let caption = "Your account "+account.username+"("+account.fullName+")has been added\n"; 
     return bot.sendPhoto(msg.from.id, account.picture, {caption:caption}); 
    }) 
    .catch(function(error){ 
     console.log(error); 
     add_account(msg,error.name); 
    }); 
}); 

在那裏我創建的標題變量的行,我試圖之前(VAR帳戶= data.params)訪問塊中創建的帳戶對象,但我得到一個參考錯誤說它沒有定義。現在,我可以通過將整個對象發送到accounts.store函數並在完成時解析對象來輕鬆繞過此操作,但對於更大的問題,這似乎是一個骯髒的解決方法。有沒有更乾淨的方法來做到這一點?

回答

1

accountundefined在第二.then(),使用data引用Promiseaccounts.store從以前.then()

.then(function(data) { 
    // `data` : `accounts.store` returned from previous `.then()` 
    let caption = "Your account " + data.username 
       + "(" + data.fullName + ")has been added\n"; 
    return bot.sendPhoto(msg.from.id, data.picture, {caption:caption}); 
}) 
+0

是什麼讓你認爲'store'返回'account'一個(用於許諾)之後,你可以只返回帳戶? – Bergi

+0

@Bergi _「是什麼讓你覺得商店返回(承諾)的帳戶」_不確定你的意思?答案的要點是,如果OP需要訪問前一個'.then()'中的值,則前面的'.then()'返回的值是後續的.then()'中的參數。 OP需要確保他們在後續的'.then()' – guest271314

+0

返回正確的值,但是他們'返回accounts.store(...)'而不是'account',所以這不太容易。 – Bergi

1

您可以創建變量返回(並將其設置在允諾)的主要功能,或者您可以返回此作爲第一個承諾的結果而不是函數的結果store

0

您可以將它傳遞給數組並在參數中使用destructuring來解包數組。

accounts.login_account(username,password).then(function(data){ 
    var account = data.params; 
    console.log(account); 
    return [account, accounts.store(msg.from.id,username,password,account.followerCount)]; 
}).then(function([account, data]){ 
    let caption = "Your account "+account.username+"("+account.fullName+")has been added\n"; 
    return bot.sendPhoto(msg.from.id, account.picture, {caption:caption}); 
}) 

你不會真的出現使用data,因此調用store

+0

第一個提出的解決方案在承諾背景下是危險的。當函數'store'返回promise時,承諾鏈將被破壞。 – hsd

+0

您需要使用'Promise.all'來確保數組中的所有promise都在等待 – Bergi

相關問題