使用Promise时这两种方法有什么区别吗?

时间:2018-01-31 09:49:31

标签: javascript promise

我刚刚更改了代码,使代码看起来更好。使用Promise时这两种方法有什么区别吗?我只是害怕它是否会影响程序逻辑。非常感谢。

代码更改前:

Dim aIntersect() As String
Dim iLoop1 As Integer, iLoop2 As Integer
Dim bTest As Boolean
Dim iOutput As Integer

'Copy everything from a1 to aIntersect
iOutput = LBound(aIntersect)
For iLoop1 = LBound(a1) To UBound(a1)
    aIntersect(iOutput) = a1(iLoop1)
    iOutput = iOutput + 1
Next iLoop1
'Add the missing items from a2
For iLoop2 = LBound(a2) To UBound(a2)
    bTest = True ' Reset test
    For iLoop1 = LBound(a1) To UBound(a1)
        If a1(iLoop1) = a2(iLoop2) Then
            bTest = False 'Already exists
            Exit For 'No need to test further
        End If
    Next iLoop1
    If bTest Then 'If it did not exists, insert it
        aIntersect(iOutput) = a2(iLoop1)
        iOutput = iOutput + 1
    End If
Next iLoop1
'aIntersect now contains everything from a1, and anything from a2 that was not already in a1

更改后的代码:(更新)

function clearTableDemo(tableName) {
    return new Promise((resolve, reject) => {
        if (db) {
            db.executeSql('DELETE FROM '+ tableName, [],
                () => { resolve () },
                err => { reject() }
            );
        } else {
            reject('db no open');
        }
    });
}

1 个答案:

答案 0 :(得分:6)

这两个函数完全不同,第二个示例根本不返回Promise。

简化功能可以做的是,例如,以下代码:

function clearTableDemo(tableName) {
    if (!db) {
        return Promise.reject('db no open');
    }
    return new Promise((resolve, reject) => {
        db.executeSql('DELETE FROM '+ tableName, [], resolve, reject);
    });
}