NodeJS - 等待回调完成

时间:2017-06-27 09:03:55

标签: node.js express

Pusedo代码:

Public Function conv_FileToByte(ByVal filename As String)

    Dim convFileToByte_array() As Byte
    Dim fs As New FileStream(filename, FileMode.Open, FileAccess.Read)
    Dim fileData As Byte() = New Byte(fs.Length - 1) {}

    Console.WriteLine("reading file data")
    fs.Read(fileData, 0, Convert.ToInt32(fs.Length))
    fs.Close()
    Console.WriteLine("close stream")


    convFileToByte_array = fileData

    Console.WriteLine("Returning value")

    Return convFileToByte_array

End Function


Public Function conv_ByteToBin(ByVal conv() As Byte)

    'Dim newBin As New List(Of String)
    Dim newBin As String = Nothing
    For Each c In conv
        'newBin.Add(Convert.ToString(c, 2).PadLeft(8, "0"))
        Dim temp_bin As String
        temp_bin = Convert.ToString(c, 2).PadLeft(8, "0")
        newBin = newBin & temp_bin
    Next
    Console.WriteLine("Returning value")

    Return newBin
End Function


Public Function conv_BinToByte(ByVal binValue As String)


    Dim count_binValue As String = binValue.Count

    Dim temp_binValue As New List(Of String)


    Dim bins As New Byte()
    Dim binlist As New List(Of Byte)

    For i As Integer = 0 To count_binValue - 1 Step 8


        Dim temp_value As String
        temp_value = binValue.Substring(i, 8)


        Dim convert_temp As String

        convert_temp = Convert.ToInt32(temp_value, 2)

        temp_binValue.Add(convert_temp)
    Next

    For Each bl In temp_binValue
        binlist.Add(bl)
    Next


    Dim binData As Byte() = New Byte(binlist.Count - 1) {}
    For bd As Integer = 0 To binlist.Count - 1
        binData(bd) = binlist(bd)
    Next

    Return binData

End Function

如何确保仅在解决所有回调后调用app.get('/', (req, res) => { request(url, callback1) //callback1 alters 'index' template a bit request(url, callback2) //callback2 alters 'index' template a bit request(url, callback3) //callback3 alters 'index' template a bit res.render('index'); //Have to render after callback1,2,3 are done });

PS。每次通话的网址都不同。

3 个答案:

答案 0 :(得分:3)

您可以使用request-promise

app.get('/', (req, res) => {
  request(url)
    .then(callback1)
    .then(() => request(url))
    .then(callback2)
    .then(() => request(url))
    .then(callback3)
    .then(() => res.render('index'));
 });

答案 1 :(得分:2)

您可以为所有异步调用维护一个计数器,并在计数器等于异步调用次数时呈现res。

以下是相同的代码段:

id="target"

如果要在每个回调中完成的任务相同,您可以在网址上使用for循环而不是编写不同的请求阻止。

答案 2 :(得分:-1)

节点承诺模块将很有帮助。 通过使用该模块,可以在执行所有回调后发送响应。