JavaScript中Promise使用

定義

Promise對象用於包裝異步函數執行結果,以便用同步的方式處理其結果。javascript

var mypromise = new Promise(function(resolve, reject){
 // asynchronous code to run here
 // call resolve() to indicate task successfully completed
 // call reject() to indicate task has failed 
})
mypromise.then(
    function(successurl){
        document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
    },
    function(errorurl){
        console.log('Error loading ' + errorurl)
    }
)

promise 包含3種狀態:java

pending: 初始狀態數組

fulfilled:  完成狀態promise

rejected: 失敗狀態app

鏈式調用方法

then()返回一個Promise對象 或者構造一個空白的Promise對象(如Promise.resolve()返回一個初始狀態是fulfilled的延遲對象)異步

處理延遲對象數組

var twodoggypromises = [getImage('dog1.png'), getImage('dog2.png')]
Promise.all(twodoggypromises).then(function(urls){
    console.log(urls) // logs ['dog1.png', 'dog2.png']
}).catch(function(urls){ // if any image fails to load, then() is skipped and catch is called
    console.log(urls) // returns array of images that failed to load
})

Promise.all([]) 參數傳入Promise對象數組 then中獲得結果的數組 Promise.all() takes an iterable (array or array-like list) of promise objects, and waits until all of those promises have been fulfilled before moving on to any then() method attached to it. The then() method is passed an array of returned values from each promise.async

解決Promise數組 有一個執行失敗 就進入catch問題

使用map函數

var doggies = ['dog1.png', 'dog2.png', 'dog3.png', 'dog4.png', 'dog5.png']
var doggypromises = doggies.map(getImage) // call getImage on each array element and return array of promises
var sequence = Promise.resolve()
 
doggypromises.forEach(function(curPromise){ // create sequence of promises to act on each one in succession
    sequence = sequence.then(function(){
        return curPromise
    }).then(function(url){
        var dog = document.createElement('img')
        dog.setAttribute('src', url)
        doggyplayground.appendChild(dog)
    }).catch(function(err){
        console.log(err + ' failed to load!')
    })
})
相關文章
相關標籤/搜索