簡體   English   中英

混淆了如何使用.then()使用promises鏈接查詢

[英]Confused on how to chain queries using promises using .then()

我似乎無法用承諾鏈接查詢鏈接。 令我困惑的是.then(function(doSomething)部分。

我應該把什么放在函數中(doSomething)? 它做了什么?

有人可以在不使用Promise.all的情況下為我鏈接這些查詢,而是使用.then()嗎? 所以我可以從中吸取教訓

SELECT * FROM books where book_id = $1

SELECT * FROM username where username = $2

SELECT * FROM saved where saved_id = $3

function(doSomething)在前一個promise成功完成時運行, doSomething是響應。 你可以連使用的承諾, then這樣的:

query("SELECT * FROM books where book_id = $1")
  .then(() => query("SELECT * FROM username where username = $2"))
  .then(() => query("SELECT * FROM saved where saved_id = $3"));

這將按順序執行三個SQL查詢。

但是,由於您很可能希望保存響應,因此可以使用async/await來簡化:

async function threeQueries() {

  //Fetch all three queries in sequence
  let queryOne = await query("SELECT * FROM books where book_id = $1");
  let queryTwo = await query("SELECT * FROM username where username = $2");
  let queryThree = await query("SELECT * FROM saved where saved_id = $3");

  //Extract the response text from our queries
  let resultOne = await queryOne.text();
  let resultTwo = await queryTwo.text();
  let resultThree = await queryThree.text();

  //Return the responses from the function
  return [resultOne, resultTwo, resultThree];

}

您也可以像這樣使用Promise.all

Promise.all([
  query("SELECT * FROM books where book_id = $1"), 
  query("SELECT * FROM username where username = $2"), 
  query("SELECT * FROM saved where saved_id = $3")
]);

Promises的目的是實現異步操作的更好的流控制。 對於在代碼流可以繼續之前,您必須以任何順序完成多個任務的情況,請使用Promise.all。 當您有多個異步任務時,請使用Promise.then,其中每個步驟可能部分取決於之前的結果(例如,在查詢您的books表后,您使用books.savedByUserId查詢用戶名表以獲取相應的用戶記錄)。

引用一些示例來自: https ://codeburst.io/node-js-mysql-and-promises-4c3be599909b作者提供了一個簡單的mySql包裝器,它返回Promises(database.query返回新的Promise)。

//In this example Promise.all executes the queries independently, but provides an
//effective tool to resume your work after all are completed. The order in which
//they complete may be random/indeterminate.
var bookQuery = database.query( 'SELECT * FROM books where book_id = $1' );
var userQuery = database.query( 'SELECT * FROM username where username = $2' );
var saveQuery = database.query( 'SELECT * FROM saved where saved_id = $3' );

Promise.all([bookQuery,userQuery,saveQuery]).then(function(results){
    //resume whatever processing that should happen afterwards
    //For instance, perhaps form fields in your UI require these datasets to be loaded
    //before displaying the UI.
    myDialog.open()
});

// In this example, things are done sequentially, this makes the most sense 
// when the result of each operation feeds into the next. Since your queries don't
// rely on each other, this is not ideally depicted.
let bookRows, userRows, savedRows ;
database.query( 'SELECT * FROM books where book_id = $1' )
    .then( rows => {
        bookRows = rows;
        return database.query( 'SELECT * FROM username where username = $2' );
    })
    .then( rows => {
        userRows = rows;
        return database.query( 'SELECT * FROM saved where saved_id = $3' );
    })
    .then( rows => {
        savedRows = rows;
        return database.close();
    })
    .then( () => {
        // do something with bookRows, userRows, savedRows
    }
    .catch( err => {
        // handle the error
    })

ps不要混淆水域,但在這種情況下,三個連續的SQL查詢可能會被一個帶連接的查詢所取代,但我想這不是問題的關鍵點。 讓我們假裝分開商店的三個查詢,這是有道理的。

我們使用promises,這些promise是將來某個時間可能產生單個值的對象。

當您運行query("query string") ,它將異步返回Promise對象。 意思是,您的應用程序不會等待查詢完成。 它將開始查詢過程並繼續下一行代碼。

那么,我們如何在完成后處理查詢?

then我們使用它來處理查詢返回的信息。 then將在查詢成功完成其進程時觸發。

暫無
暫無

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

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