簡體   English   中英

循環內的承諾鏈

[英]Promise chain inside loop

我是Java語言的新手。 我對諾言鏈有疑問。 我正在嘗試在for loop內執行鏈承諾,我想要這樣的輸出:

一二三--------一二三--------一二三

但是我總是得到這樣的輸出

一二-------一二-------一二-------三三三

這是我的代碼:

test(item: any, i: number){

    this.filePath = item.rows.item(i).filepath;
    this.fileName = this.filePath.substr(this.filePath.lastIndexOf('/') + 1);
    this.imgePath = this.filePath.replace(this.fileName, "");


    console.log(this.filePath)
    console.log(this.fileName)
    console.log(this.imgePath)

    const one = new Promise<boolean>(resolve => {
        this.readfile.checkFile(this.imgePath, this.fileName).then(isExists => {
            console.log("one")
            resolve(isExists);
        })
    });

    const two = one.then(isExists => {
        console.log("two")
        if (isExists) {
            return this.readfile.readAsDataURL(this.imgePath, this.fileName).then(res =>{
                return res;
            })
        }
        else {
            console.log("not exists")
        }
    })

    const three = two.then(res => {
        console.log("three")
        this.base64Image.push(res);
    })
}

process(item: any, rows: number) {
    let prom: Promise<void>[] = [];

    for (let i = 0; i < rows; i++) {
        this.test(item,i);
        console.log(i,"loop")
    }
}

誰能幫我? 我花了8個小時,但仍然無法解決。 謝謝!

在執行循環中的下一項之前,您無需等待諾言完成。

除非您希望並行執行異步代碼或正在使用async await否則不應將for循環與異步代碼一起使用。

需要更改:

您的測試方法應返回promise,以便我們可以跟蹤何時實現promise。

在執行下一個測試方法之前,您需要等待上一個測試方法返回的承諾得以實現。

test(item: any, i: number){

    this.filePath = item.rows.item(i).filepath;
    this.fileName = this.filePath.substr(this.filePath.lastIndexOf('/') + 1);
    this.imgePath = this.filePath.replace(this.fileName, "");


    console.log(this.filePath)
    console.log(this.fileName)
    console.log(this.imgePath)

    const one = new Promise<boolean>(resolve => {
        this.readfile.checkFile(this.imgePath, this.fileName).then(isExists => {
            console.log("one")
            resolve(isExists);
        })
    });

    const two = one.then(isExists => {
        console.log("two")
        if (isExists) {
            return this.readfile.readAsDataURL(this.imgePath, this.fileName).then(res =>{
                return res;
            })
        }
        else {
            console.log("not exists")
        }
    })

    const three = two.then(res => {
        console.log("three")
        this.base64Image.push(res);
    })

    return three;
}

process(item: any, rows: number) {
    let prom = Promise.resolve();

    for (let i = 0; i < rows; i++) {
        prom = prom.then(() => this.test(item,j));
        console.log(i,"loop")
    }
}

暫無
暫無

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

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