javascript e7异步等待返回

时间:2018-01-30 18:09:48

标签: javascript ajax async-await return

我是javascript中async / await的新手。在下面的代码中,我有一个async函数和一个解析的jquery ajax调用。但是,当我返回 cart 变量并将其设置为 arr 时,我在控制台中首先显示一个未定义的值,这意味着console.log(arr)是之前开火如何将此值返回到 arr ,并处理该变量?

String      ACCESS_KEY="****************",
        SECRET_KEY="****************",
        MY_BUCKET="bucket_name",
        OBJECT_KEY="unique_id";              


AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
            AmazonS3 s3 = new AmazonS3Client(credentials);
            java.security.Security.setProperty("networkaddress.cache.ttl" , "60");
            s3.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));
            s3.setEndpoint("https://s3-ap-southeast-1.amazonaws.com/");
            List<Bucket> buckets=s3.listBuckets();
            for(Bucket bucket:buckets){
                Log.e("Bucket ","Name "+bucket.getName()+" Owner "+bucket.getOwner()+ " Date " + bucket.getCreationDate());
            }
            Log.e("Size ", "" + s3.listBuckets().size());
            TransferUtility transferUtility = new TransferUtility(s3, getApplicationContext());
            UPLOADING_IMAGE=new File(Environment.getExternalStorageDirectory().getPath()+"/Screenshot.png");
            TransferObserver observer = transferUtility.upload(MY_BUCKET,OBJECT_KEY,UPLOADING_IMAGE);
            observer.setTransferListener(new TransferListener() {
                @Override
                public void onStateChanged(int id, TransferState state) {
                    // do something
                    progress.hide();
                    path.setText("ID "+id+"\nState "+state.name()+"\nImage ID "+OBJECT_KEY);

                }

                @Override
                public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                    int percentage = (int) (bytesCurrent / bytesTotal * 100);
                    progress.setProgress(percentage);
                    //Display percentage transfered to user
                }

                @Override
                public void onError(int id, Exception ex) {
                    // do something
                    Log.e("Error  ",""+ex );
                }

            });

我觉得我应该能够从函数中返回值,然后继续我的代码。

2 个答案:

答案 0 :(得分:0)

$.ajax({
    url: http,
    method: "GET"
  }).promise()

试试这个。

答案 1 :(得分:0)

除非将其包装在异步函数中,否则不能使用await。

// ... your code
const main = async function() {
 // put the main body of your code here
 const arr = await what(http);
 console.log(arr)
}

main()

以下是您应该阅读的有关使用async / await with jQuery

的文章

http://petetasker.com/using-async-await-jquerys-ajax/